
#include <string>
#include <vector>
#include <GL/glew.h>
#include <glm/glm.hpp>
#include <boost/lexical_cast.hpp>
#include <ptr.hpp>

#include "Font.hpp"

namespace zen {

	namespace video {

		Font::Font(): pixelSize(0), glyphCount(0) {
		}

		Font::Font(const PTexture &texture, int textureSize, const arr(glm::ivec3) &steps, const arr(glm::ivec4) &rects, int glyphCount) {
			this->texture = texture;
			this->pixelSize = 1.0f / textureSize;
			this->steps = steps;
			this->rects = rects;
			this->glyphCount = glyphCount;
		}

		Font::~Font() {
		}

		void Font::drawText(const std::string &text, float x, float y, float depth) const {
			glBindTexture(GL_TEXTURE_2D, texture->getHandle());
			glBegin(GL_QUADS);
			glm::ivec3* steps = this->steps.get();
			for (unsigned int i = 0; i < text.length(); i++) {
				unsigned char ch = (unsigned char)text[i];
				glm::ivec3 step = steps[ch];
				glm::ivec4 rect = rects[ch];
				float cx = x + step[1], cy = y - step[2];
				glTexCoord2f(rect[0] * pixelSize, rect[1] * pixelSize);
				glVertex3f(cx, cy, depth);
				glTexCoord2f(rect[0] * pixelSize, (rect[1] + rect[3]) * pixelSize);
				glVertex3f(cx, cy + rect[3], depth);
				glTexCoord2f((rect[0] + rect[2]) * pixelSize, (rect[1] + rect[3]) * pixelSize);
				glVertex3f(cx + rect[2], cy + rect[3], depth);
				glTexCoord2f((rect[0] + rect[2]) * pixelSize, rect[1] * pixelSize);
				glVertex3f(cx + rect[2], cy, depth);
				x += step[0];
			}
			glEnd();
		}

		int Font::getTextWidth(const std::string &text) const {
			int width = 0;
			glm::ivec3* steps = this->steps.get();
			for (unsigned int i = 0; i < text.length(); i++)
				width += steps[(unsigned char)text[i]][0];
			return width;
		}
		
	} // namespace video

} // namespace zen
